#include "Item.hh" // 包含物品头文件，定义了Item类，用于角色背包和装备 / Include Item header, defines Item class for character's inventory and equipment
#include "Character.hh" // 包含角色头文件，定义了Character类和ICharacter接口 / Include Character header, defines Character class and ICharacter interface
#include <iostream> // 包含输入输出库，用于打印信息到屏幕 / Include input-output library for printing info to the screen
#include <vector> // 包含向量库，用于存储背包中的物品列表 / Include vector library for storing list of items in inventory

// 构造函数：创建角色，初始化名字、描述、生命值、攻击力、防御力和无敌状态
// Constructor: Creates a character, initializes name, description, health, attack, defense, and invincibility
Character::Character(std::string n, std::string desc, 
                    unsigned hp, unsigned maxHp,
                    unsigned atk, unsigned def, bool inv)
    : name(n), // 设置角色名字，比如“Adventurer” / Set character name, e.g., "Adventurer"
      description(desc), // 设置角色描述，介绍角色的背景 / Set character description, explains character's background
      health(hp), // 设置当前生命值，表示角色还剩多少生命 / Set current health, shows how much life remains
      maxHealth(maxHp), // 设置最大生命值，角色的生命上限 / Set maximum health, the character's health limit
      attackPower(atk), // 设置攻击力，决定攻击造成的伤害 / Set attack power, determines damage dealt in attacks
      defense(def), // 设置防御力，减少受到的伤害 / Set defense, reduces damage taken
      equippedWeapon(nullptr), // 初始化武器为空（未装备） / Initialize equipped weapon to nullptr (none equipped)
      equippedArmor(nullptr), // 初始化盔甲为空（未装备） / Initialize equipped armor to nullptr (none equipped)
      invincible(inv) // 设置是否无敌，无敌时不受伤害 / Set invincibility, invincible characters take no damage
{
    // 背包（inventory）在定义时已自动初始化为空向量，无需额外操作
    // Inventory is automatically initialized as an empty vector, no extra action needed
}

// 析构函数：当角色对象销毁时，清理背包中的物品内存
// Destructor: When character object is destroyed, free memory for items in inventory
Character::~Character() {
    for (Item* item : inventory) { // 遍历背包中的每个物品 / Loop through each item in inventory
        delete item; // 释放物品的内存（因为物品是用new动态分配的） / Free item's memory (items are dynamically allocated with new)
    }
    // 背包向量会在销毁时自动清空，无需手动清理 / Inventory vector is automatically cleared upon destruction
}

// 检查是否存活：判断角色是否还有生命值
// Check if alive: Determine if character still has health
bool Character::isAlive() const { 
    return health > 0; // 如果生命值大于0，返回true（活着） / Return true if health > 0 (alive)
}

// 受到伤害：根据伤害值和防御力减少生命值
// Take damage: Reduce health based on damage and defense
bool Character::takeDamage(unsigned damage) {
    if (invincible) return true; // 如果角色无敌，直接返回true（活着），不受伤害 / If character is invincible, return true (alive), no damage taken
    unsigned effectiveDamage = (damage > defense) ? (damage - defense) : 0; // 计算实际伤害：伤害减去防御，最小为0 / Calculate effective damage: damage minus defense, minimum 0
    if (effectiveDamage >= health) { // 如果实际伤害大于或等于当前生命值 / If effective damage is greater than or equal to current health
        health = 0; // 生命值设为0（角色死亡） / Set health to 0 (character dies)
    } else { // 如果实际伤害小于当前生命值 / If effective damage is less than current health
        health -= effectiveDamage; // 减少生命值 / Subtract effective damage from health
    }
    return isAlive(); // 返回角色是否存活 / Return whether character is alive
}

// 攻击目标：对另一个角色造成伤害
// Attack target: Deal damage to another character
bool Character::attack(ICharacter& target) {
    if (!isAlive()) return false; // 如果自身已死亡，无法攻击，返回false / If character is dead, can't attack, return false
    std::cout << name << " attacks " << target.getName() << "!\n"; // 打印攻击信息，比如“Adventurer attacks Creeper!” / Print attack message, e.g., "Adventurer attacks Creeper!"
    return target.takeDamage(attackPower); // 让目标受到攻击力值的伤害，返回目标是否存活 / Make target take damage equal to attack power, return if target is alive
}

// 获取名字：返回角色的名称
// Get name: Return character's name
std::string Character::getName() const { 
    return name; // 直接返回存储的名字 / Directly return stored name
}

// 获取描述：返回角色的背景描述
// Get description: Return character's background description
std::string Character::getDescription() const { 
    return description; // 直接返回存储的描述 / Directly return stored description
}

// 获取生命值：返回当前生命值
// Get health: Return current health
unsigned Character::getHealth() const { 
    return health; // 直接返回当前生命值 / Directly return current health
}

// 获取攻击力：返回当前攻击力
// Get attack: Return current attack power
unsigned Character::getAttack() const { 
    return attackPower; // 直接返回当前攻击力 / Directly return current attack power
}

// 获取防御力：返回当前防御力
// Get defense: Return current defense
unsigned Character::getDefense() const { 
    return defense; // 直接返回当前防御力 / Directly return current defense
}

// 返回角色信息：生成描述角色的字符串
// Return character info: Generate a string describing the character
std::string Character::toString() const {
    return name + " (Health: " + std::to_string(health) + "/" 
           + std::to_string(maxHealth) + ", Attack: " 
           + std::to_string(attackPower) + ", Defense: " 
           + std::to_string(defense) 
           + (invincible ? ", Invincible" : "") + ")";
    // 格式：名字 (生命: 当前/最大, 攻击: 值, 防御: 值, [无敌]) / Format: Name (Health: current/max, Attack: value, Defense: value, [Invincible])
}

// 添加物品：将物品加入背包
// Add item: Add an item to the inventory
void Character::addToInventory(Item* item) {
    inventory.push_back(item); // 将物品指针添加到背包列表末尾 / Add item pointer to the end of inventory list
    std::cout << "Obtained " << item->name << "!\n"; // 打印获得物品的消息，比如“Obtained Wooden Sword!” / Print message for obtaining item, e.g., "Obtained Wooden Sword!"
}

// 装备或使用物品：从背包中选择物品装备或使用
// Equip or use item: Select an item from inventory to equip or use
void Character::equipItem(size_t index) {
    if (index >= inventory.size()) { // 检查索引是否有效（不能超出背包大小） / Check if index is valid (can't exceed inventory size)
        std::cout << "Invalid item number!\n"; // 如果无效，打印错误消息 / If invalid, print error message
        return; // 退出函数 / Exit function
    }
    
    Item* item = inventory[index]; // 获取指定索引的物品 / Get item at specified index
    
    if (item->attackBonus > 0) { // 如果物品有攻击加成，说明是武器 / If item has attack bonus, it's a weapon
        if (equippedWeapon) { // 如果已经装备了武器 / If a weapon is already equipped
            attackPower -= equippedWeapon->attackBonus; // 移除之前武器的攻击加成 / Remove previous weapon's attack bonus
        }
        equippedWeapon = item; // 装备新武器 / Equip new weapon
        attackPower += item->attackBonus; // 增加新武器的攻击加成 / Add new weapon's attack bonus
        std::cout << "Equipped weapon: " << item->name << "\n"; // 打印装备武器的消息 / Print message for equipping weapon
    } 
    else if (item->defenseBonus > 0) { // 如果物品有防御加成，说明是盔甲 / If item has defense bonus, it's armor
        if (equippedArmor) { // 如果已经装备了盔甲 / If armor is already equipped
            defense -= equippedArmor->defenseBonus; // 移除之前盔甲的防御加成 / Remove previous armor's defense bonus
        }
        equippedArmor = item; // 装备新盔甲 / Equip new armor
        defense += item->defenseBonus; // 增加新盔甲的防御加成 / Add new armor's defense bonus
        std::cout << "Equipped armor: " << item->name << "\n"; // 打印装备盔甲的消息 / Print message for equipping armor
    } 
    else if (item->healthBonus > 0) { // 如果物品有生命加成，说明是消耗品（如药水） / If item has health bonus, it's a consumable (e.g., potion)
        health += item->healthBonus; // 增加生命值 / Increase health
        if (health > maxHealth) health = maxHealth; // 确保生命值不超过最大值 / Ensure health doesn't exceed max
        std::cout << "Used " << item->name << ", health restored!\n"; // 打印使用物品的消息 / Print message for using item
        delete inventory[index]; // 释放物品内存（消耗品用完即销毁） / Free item memory (consumable is destroyed after use)
        inventory.erase(inventory.begin() + index); // 从背包移除物品 / Remove item from inventory
    }
}

// 获取装备的武器：返回武器名字或“None”
// Get equipped weapon: Return weapon name or "None"
std::string Character::getEquippedWeapon() const {
    return equippedWeapon ? equippedWeapon->name : "None"; // 如果有武器，返回名字，否则返回“None” / Return weapon name if equipped, else "None"
}

// 获取装备的盔甲：返回盔甲名字或“None”
// Get equipped armor: Return armor name or "None"
std::string Character::getEquippedArmor() const {
    return equippedArmor ? equippedArmor->name : "None"; // 如果有盔甲，返回名字，否则返回“None” / Return armor name if equipped, else "None"
}

// 移除物品：从背包中移除指定数量的指定物品
// Remove item: Remove a specified number of items with a given name from inventory
bool Character::removeItem(const std::string& itemName, int count) {
    int foundCount = 0; // 记录找到的匹配物品数量 / Track number of matching items found
    std::vector<size_t> indices; // 存储匹配物品的索引 / Store indices of matching items
    
    for (size_t i = 0; i < inventory.size(); ++i) { // 遍历背包 / Loop through inventory
        if (inventory[i]->name == itemName) { // 如果物品名字匹配 / If item name matches
            indices.push_back(i); // 记录物品索引 / Record item index
            foundCount++; // 增加找到的计数 / Increment found count
            if (foundCount == count) break; // 如果找到足够数量，停止搜索 / If found enough items, stop searching
        }
    }
    
    if (foundCount < count) return false; // 如果找到的物品不足，返回false / If not enough items found, return false
    
    for (int i = count - 1; i >= 0; --i) { // 从后向前遍历要移除的物品索引 / Loop through indices to remove in reverse
        if (inventory[indices[i]] == equippedWeapon) { // 如果物品是当前装备的武器 / If item is currently equipped weapon
            attackPower -= equippedWeapon->attackBonus; // 移除武器的攻击加成 / Remove weapon's attack bonus
            equippedWeapon = nullptr; // 清空装备的武器 / Clear equipped weapon
        }
        if (inventory[indices[i]] == equippedArmor) { // 如果物品是当前装备的盔甲 / If item is currently equipped armor
            defense -= equippedArmor->defenseBonus; // 移除盔甲的防御加成 / Remove armor's defense bonus
            equippedArmor = nullptr; // 清空装备的盔甲 / Clear equipped armor
        }
        delete inventory[indices[i]]; // 释放物品内存 / Free item memory
        inventory.erase(inventory.begin() + indices[i]); // 从背包移除物品 / Remove item from inventory
    }
    return true; // 返回true，表示成功移除 / Return true, indicating successful removal
}

// 显示背包：打印背包中的物品列表
// Display inventory: Print list of items in inventory
void Character::displayInventory() const {
    if (inventory.empty()) { // 如果背包为空 / If inventory is empty
        std::cout << "Inventory is empty.\n"; // 打印“背包为空” / Print "Inventory is empty"
    } else { // 如果背包有物品 / If inventory has items
        std::cout << "Inventory:\n"; // 打印“背包：”标题 / Print "Inventory:" title
        for (size_t i = 0; i < inventory.size(); ++i) { // 遍历背包物品 / Loop through inventory items
            std::string bonus = ""; // 初始化加成描述为空 / Initialize bonus description as empty
            if (inventory[i]->attackBonus > 0) { // 如果物品有攻击加成 / If item has attack bonus
                bonus = " (+" + std::to_string(inventory[i]->attackBonus) + " Attack)"; // 显示攻击加成 / Show attack bonus
            } else if (inventory[i]->defenseBonus > 0) { // 如果物品有防御加成 / If item has defense bonus
                bonus = " (+" + std::to_string(inventory[i]->defenseBonus) + " Defense)"; // 显示防御加成 / Show defense bonus
            } else if (inventory[i]->healthBonus > 0) { // 如果物品有生命加成 / If item has health bonus
                bonus = " (+" + std::to_string(inventory[i]->healthBonus) + " Health)"; // 显示生命加成 / Show health bonus
            }
            std::cout << i + 1 << ". " 
                      << inventory[i]->name << ": " 
                      << inventory[i]->description 
                      << bonus << "\n"; // 打印物品信息：编号、名字、描述、加成 / Print item info: number, name, description, bonus
        }
    }
}

// 显示角色信息：打印角色的详细信息
// Display character info: Print detailed character information
void Character::display() const {
    std::cout << toString() << "\n" // 打印角色状态（名字、生命、攻击、防御等） / Print character status (name, health, attack, defense, etc.)
              << "Description: " << description << "\n"; // 打印角色描述 / Print character description
}